import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'

// 定义并导出 Store
export const useCartStore = defineStore('cart', () => {
  // 从localStorage中取出购物车列表
  const cartList = ref(JSON.parse(localStorage.getItem('cart') || '[]'))

  // 计算总价
  const totalPrice = computed(() => {
    //   reduce(     回调函数, 初始值 )
    return cartList.value.reduce((total, item) => {
      return total + (item.price * item.count)
    }, 0)
  })

  // 计算总数量
  const totalCount = computed(() => {
    return cartList.value.reduce((total, item) => {
      return total + item.count
    }, 0)
  })

  // 添加到购物车
  const addToCart = (product) => {
    // 先判断商品是否已存在
    const item = cartList.value.find(item => item.id === product.id)
    if (item) {
      // 已存在则数量+1
      item.count++
    } else {
      // 不存在则添加
      cartList.value.push({
        id: product.id,
        name: product.pname,
        price: product.price,
        image_url: product.pic,
        count: 1,
        selected: true
      })
    }
    ElMessage.success('添加成功')
    // 持久化存储
    saveToLocal()
  }

  // 从购物车删除
  const removeFromCart = (productId) => {
    const index = cartList.value.findIndex(item => item.id === productId)
    if (index > -1) {
      cartList.value.splice(index, 1)
      saveToLocal()
    }
  }

  // 修改商品数量
  const updateCount = (productId, count) => {
    const item = cartList.value.find(item => item.id === productId)
    if (item) {
      item.count = count
      saveToLocal()
    }
  }

  // 切换选中状态
  const toggleSelect = (productId) => {
    const item = cartList.value.find(item => item.id === productId)
    if (item) {
      item.selected = !item.selected
      saveToLocal()
    }
  }

  // 全选/取消全选
  const toggleSelectAll = (selected) => {
    cartList.value.forEach(item => { item.selected = selected })
    saveToLocal()
  }

  // 计算选中商品总价
  const selectedTotalPrice = computed(() => {
    return cartList.value
      .filter(item => item.selected)
      .reduce((total, item) => total + item.price * item.count, 0)
  })

  // 计算选中商品数量
  const selectedCount = computed(() => {
    return cartList.value
      .filter(item => item.selected)
      .reduce((total, item) => total + item.count, 0)
  })

  // 持久化到本地存储
  const saveToLocal = () => {
    // JSON.stringify() 方法用于将 JavaScript 值转换为 JSON 字符串。
    localStorage.setItem('cart', JSON.stringify(cartList.value))
  }

  // 从本地存储恢复
  const loadFromLocal = () => {
    const local = localStorage.getItem('cart')
    if (local) {
      cartList.value = JSON.parse(local)
    }
  }

  return {
    cartList,
    totalPrice,
    totalCount,
    selectedTotalPrice,
    selectedCount,
    addToCart,
    removeFromCart,
    updateCount,
    toggleSelect,
    toggleSelectAll,
    loadFromLocal
  }
})
